import requests
import json

# 测试用例数据 - 以字典形式存储多个测试用例
test_cases = [
    {
        "name": "获取用户列表 - 成功",
        "url": "https://reqres.in/api/users",
        "method": "GET",
        "params": {"page": 2},
        "expected_status": 200
    },
    {
        "name": "创建新用户 - 成功",
        "url": "https://reqres.in/api/users",
        "method": "POST",
        "headers": {"Content-Type": "application/json"},
        "body": {"name": "morpheus", "job": "leader"},
        "expected_status": 201,
        "expected_data": {"name": "morpheus", "job": "leader"}
    },
    {
        "name": "登录失败 - 缺少密码",
        "url": "https://reqres.in/api/login",
        "method": "POST",
        "headers": {"Content-Type": "application/json"},
        "body": {"email": "peter@klaven"},
        "expected_status": 400,
        "expected_error": "Missing password"
    }
]


def run_api_test(test_case):
    """执行单个测试用例并返回结果"""
    try:
        # 发送HTTP请求
        if test_case['method'] == 'GET':
            response = requests.get(
                url=test_case['url'],
                params=test_case.get('params', {})
            )
        elif test_case['method'] == 'POST':
            response = requests.post(
                url=test_case['url'],
                headers=test_case.get('headers', {}),
                json=test_case.get('body', {})
            )
        else:
            return {"status": "error", "message": "不支持的HTTP方法"}

        # 验证响应状态码
        status_ok = response.status_code == test_case['expected_status']

        # 验证响应内容（如果定义了验证规则）
        data_ok = True
        if 'expected_data' in test_case:
            response_data = response.json()
            for key, value in test_case['expected_data'].items():
                if key not in response_data or response_data[key] != value:
                    data_ok = False
                    break

        # 验证错误信息（如果定义了验证规则）
        error_ok = True
        if 'expected_error' in test_case:
            error_data = response.json()
            if 'error' not in error_data or error_data['error'] != test_case['expected_error']:
                error_ok = False

        # 返回测试结果
        return {
            "status": "passed" if status_ok and data_ok and error_ok else "failed",
            "response": {
                "status_code": response.status_code,
                "headers": dict(response.headers),
                "body": response.json() if response.content else None
            }
        }

    except Exception as e:
        return {"status": "error", "message": str(e)}


# 执行所有测试用例并输出结果
print("=" * 50)
print("接口自动化测试报告")
print("=" * 50)

for i, case in enumerate(test_cases, 1):
    result = run_api_test(case)

    print(f"\n用例 {i}: {case['name']}")
    print(f"请求: {case['method']} {case['url']}")

    if 'params' in case:
        print(f"参数: {json.dumps(case['params'])}")
    if 'body' in case:
        print(f"请求体: {json.dumps(case['body'])}")

    # 检查是否有响应信息
    if 'response' in result:
        print(f"\n实际状态码: {result['response']['status_code']}")
        print(f"预期状态码: {case['expected_status']}")

        if result['status'] == "passed":
            print("结果: \033[32m通过\033[0m")  # 绿色显示通过
        else:
            print("结果: \033[31m失败\033[0m")  # 红色显示失败

        print("\n响应内容:")
        body = result['response']['body']
        if body is not None:
            print(json.dumps(body, indent=2))
        else:
            print("无响应体")
    else:
        print(f"\n\033[31m测试执行错误: {result.get('message', '未知错误')}\033[0m")

print("\n" + "=" * 50)
print("测试执行完成")
print("=" * 50)